import "es6-promise";
import Axios from 'axios'
import * as C from "../constants/api"
import cookies from './cookies'
import {Message} from 'element-ui'
import utils from './misc'
import queryString from 'query-string'
import { puts } from "util";
import { type } from "os";

const METHODS = {
	GET: 'get',
	POST: 'post',
	PUT: 'put',
	DELETE: 'delete'
};

Axios.interceptors.request.use(config => {

	return config;
});

Axios.interceptors.response.use(response => {

    let {data: resp} = response;

	return new Promise((resolve, reject) => {
        const {errorCode} = resp;
         if ( errorCode ) {
            reject(resp);
			resp.errorMsg && Message.warning({message: resp.errorMsg, showClose: true});
        } else {
            resolve(resp)
        }
	});

}, error => {
	if (window.sso_login.checkNeedLogin(error)) {
		return false
	}
    const {response} = error
	let errorMsg = ''
	if (!response) {
		errorMsg = '网络错误，请检测网络是否正常!'
	} else {
		const { data } = response
		errorMsg = data && data.errorMsg ? data.errorMsg : '服务器发生异常，请联系管理员'
	}
    Message.warning({message: errorMsg, showClose: true});
	return Promise.reject(error);
});

const request = (url, params = {}, headers = {}, method = METHODS.GET) => {
    let options = {
		headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            // 'Content-Type': 'application/json;charset=UTF-8',
			...headers,
		},
		method: method
    };

	if (method === METHODS.POST || method == METHODS.PUT) {
		if( options.headers['Content-Type'] === 'application/json' || headers.__FILE__UPLOAD__ ) {
            options.data = params
        } else {
            options.data = queryString.stringify(params);
        }
	} else if (method === METHODS.GET || method == METHODS.DELETE) {
		options.params = params;
	}
	return Axios({url, ...options});
};

const post = (url, params, headers) => request(url, params, headers, METHODS.POST);

const deleteRequest = (url, params, headers) => request(url, params, headers, METHODS.DELETE)

const put = (url, params, headers) => request(url, params, headers, METHODS.PUT)
//日志接口请求方法
const requestLogs = (url, params = {}, headers = {}, method = METHODS.GET) => {

	let options = {
		headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            // 'Content-Type': 'application/json;charset=UTF-8',
			...headers,
		},
		method: method
	};

	options.data = params
	options.params = params;

	return Axios({url, ...options});
};


export const createAction = (type, payloadCreator, metaCreator) => {
	const identity = (...args) => args[0];
	const isFunc = (fn) => typeof(fn) === 'function';
	const isPromise = obj => typeof(obj) === 'object' && isFunc(obj.then);
	const finalPayloadCreator = isFunc(payloadCreator) ? payloadCreator : identity;

	return ({commit, dispatch}, ...args) => {

        const payload = finalPayloadCreator(...args);
		const action = {type, payload};

		if (isFunc(metaCreator)) {
			action.meta = metaCreator(...args);
		}

		if (isPromise(payload)) {
			return payload.then(result => {
				commit(type, Object.assign(action, {payload: result}));
				return result;
			}).catch(error => {
				dispatch('hidePageLoading');
				console.error(`请求 ${type}异常，请求结果为: ${JSON.stringify(error)}`);
				return Promise.reject(error);
			});
		}

		return commit(type, Object.assign(action, {payload}));
	};
};

export default {
	
	figureList :(params) =>request(C.FIGURE_LIST,params),

	figureGetOne :(params)=>request(C.FIGURE_GETONE,params),

	figureUpdate: (params)=>request(C.FIGURE_UPDATE,params),

	figureSave: (params) => request(C.FIGURE_SAVE,params),

	figureDelete : (params) => request(C.FIGURE_DELETE,params),
}


